package com.example.config;

import com.dangdang.ddframe.job.api.ElasticJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.JobTypeConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.executor.handler.JobProperties;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * @author YJC
 * @version V1.0
 * @description: job基础类配置
 * @date 2020-11-10 15:09
 */
@Configuration
public class BasicJobConfig {

    @Autowired
    private ZookeeperRegistryCenter registryCenter;


    /**
     * 构造SpringJobScheduler，job的名称使用job的类名
     *
     * @param job
     * @param jobProperties
     * @param <T>
     * @return
     */
    protected <T extends ElasticJob> SpringJobScheduler buildSpringJobScheduler(T job, JobConfigProperties jobProperties) {
        String jobName = StringUtils.isNotEmpty(jobProperties.getJobName()) ? jobProperties.getJobName() : job.getClass().getSimpleName();
        return new SpringJobScheduler(job, registryCenter, this.getLiteJobConfiguration(jobName, jobProperties));
    }

    /**
     * 构造LiteJobConfiguration配置
     *
     * @param jobName
     * @param jobProperties
     * @return
     */
    private LiteJobConfiguration getLiteJobConfiguration(String jobName, JobConfigProperties jobProperties) {
        JobCoreConfiguration jobCoreConfiguration = JobCoreConfiguration
                .newBuilder(jobName, jobProperties.getCron(), jobProperties.getShardingTotalCount())
                .shardingItemParameters(jobProperties.getShardingItemParameters())
                .description(jobProperties.getDescription())
                .misfire(jobProperties.getMisfire())
                .jobProperties(JobProperties.JobPropertiesEnum.JOB_EXCEPTION_HANDLER.getKey(), jobProperties.getJobExceptionHandler())
                .build();

        JobTypeConfiguration jobConfig = new SimpleJobConfiguration(jobCoreConfiguration, jobName);

        return LiteJobConfiguration.newBuilder(jobConfig)
                .overwrite(jobProperties.getOverwrite())
                .monitorExecution(jobProperties.getMonitorExecution())
                .build();
    }
}
